home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / logging / handlers.pyc (.txt) < prev   
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  36.8 KB  |  1,200 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. """
  5. Additional handlers for the logging package for Python. The core package is
  6. based on PEP 282 and comments thereto in comp.lang.python, and influenced by
  7. Apache's log4j system.
  8.  
  9. Copyright (C) 2001-2009 Vinay Sajip. All Rights Reserved.
  10.  
  11. To use, simply 'import logging.handlers' and log away!
  12. """
  13. import logging
  14. import socket
  15. import types
  16. import os
  17. import string
  18. import cPickle
  19. import struct
  20. import time
  21. import re
  22. from stat import ST_DEV, ST_INO
  23.  
  24. try:
  25.     import codecs
  26. except ImportError:
  27.     codecs = None
  28.  
  29. DEFAULT_TCP_LOGGING_PORT = 9020
  30. DEFAULT_UDP_LOGGING_PORT = 9021
  31. DEFAULT_HTTP_LOGGING_PORT = 9022
  32. DEFAULT_SOAP_LOGGING_PORT = 9023
  33. SYSLOG_UDP_PORT = 514
  34. _MIDNIGHT = 86400
  35.  
  36. class BaseRotatingHandler(logging.FileHandler):
  37.     '''
  38.     Base class for handlers that rotate log files at a certain point.
  39.     Not meant to be instantiated directly.  Instead, use RotatingFileHandler
  40.     or TimedRotatingFileHandler.
  41.     '''
  42.     
  43.     def __init__(self, filename, mode, encoding = None, delay = 0):
  44.         '''
  45.         Use the specified filename for streamed logging
  46.         '''
  47.         if codecs is None:
  48.             encoding = None
  49.         
  50.         logging.FileHandler.__init__(self, filename, mode, encoding, delay)
  51.         self.mode = mode
  52.         self.encoding = encoding
  53.  
  54.     
  55.     def emit(self, record):
  56.         '''
  57.         Emit a record.
  58.  
  59.         Output the record to the file, catering for rollover as described
  60.         in doRollover().
  61.         '''
  62.         
  63.         try:
  64.             if self.shouldRollover(record):
  65.                 self.doRollover()
  66.             
  67.             logging.FileHandler.emit(self, record)
  68.         except (KeyboardInterrupt, SystemExit):
  69.             raise 
  70.         except:
  71.             self.handleError(record)
  72.  
  73.  
  74.  
  75.  
  76. class RotatingFileHandler(BaseRotatingHandler):
  77.     '''
  78.     Handler for logging to a set of files, which switches from one file
  79.     to the next when the current file reaches a certain size.
  80.     '''
  81.     
  82.     def __init__(self, filename, mode = 'a', maxBytes = 0, backupCount = 0, encoding = None, delay = 0):
  83.         '''
  84.         Open the specified file and use it as the stream for logging.
  85.  
  86.         By default, the file grows indefinitely. You can specify particular
  87.         values of maxBytes and backupCount to allow the file to rollover at
  88.         a predetermined size.
  89.  
  90.         Rollover occurs whenever the current log file is nearly maxBytes in
  91.         length. If backupCount is >= 1, the system will successively create
  92.         new files with the same pathname as the base file, but with extensions
  93.         ".1", ".2" etc. appended to it. For example, with a backupCount of 5
  94.         and a base file name of "app.log", you would get "app.log",
  95.         "app.log.1", "app.log.2", ... through to "app.log.5". The file being
  96.         written to is always "app.log" - when it gets filled up, it is closed
  97.         and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc.
  98.         exist, then they are renamed to "app.log.2", "app.log.3" etc.
  99.         respectively.
  100.  
  101.         If maxBytes is zero, rollover never occurs.
  102.         '''
  103.         if maxBytes > 0:
  104.             mode = 'a'
  105.         
  106.         BaseRotatingHandler.__init__(self, filename, mode, encoding, delay)
  107.         self.maxBytes = maxBytes
  108.         self.backupCount = backupCount
  109.  
  110.     
  111.     def doRollover(self):
  112.         '''
  113.         Do a rollover, as described in __init__().
  114.         '''
  115.         self.stream.close()
  116.         if self.backupCount > 0:
  117.             for i in range(self.backupCount - 1, 0, -1):
  118.                 sfn = '%s.%d' % (self.baseFilename, i)
  119.                 dfn = '%s.%d' % (self.baseFilename, i + 1)
  120.                 if os.path.exists(sfn):
  121.                     if os.path.exists(dfn):
  122.                         os.remove(dfn)
  123.                     
  124.                     os.rename(sfn, dfn)
  125.                     continue
  126.             
  127.             dfn = self.baseFilename + '.1'
  128.             if os.path.exists(dfn):
  129.                 os.remove(dfn)
  130.             
  131.             os.rename(self.baseFilename, dfn)
  132.         
  133.         self.mode = 'w'
  134.         self.stream = self._open()
  135.  
  136.     
  137.     def shouldRollover(self, record):
  138.         '''
  139.         Determine if rollover should occur.
  140.  
  141.         Basically, see if the supplied record would cause the file to exceed
  142.         the size limit we have.
  143.         '''
  144.         if self.stream is None:
  145.             self.stream = self._open()
  146.         
  147.         if self.maxBytes > 0:
  148.             msg = '%s\n' % self.format(record)
  149.             self.stream.seek(0, 2)
  150.             if self.stream.tell() + len(msg) >= self.maxBytes:
  151.                 return 1
  152.         
  153.         return 0
  154.  
  155.  
  156.  
  157. class TimedRotatingFileHandler(BaseRotatingHandler):
  158.     '''
  159.     Handler for logging to a file, rotating the log file at certain timed
  160.     intervals.
  161.  
  162.     If backupCount is > 0, when rollover is done, no more than backupCount
  163.     files are kept - the oldest ones are deleted.
  164.     '''
  165.     
  166.     def __init__(self, filename, when = 'h', interval = 1, backupCount = 0, encoding = None, delay = 0, utc = 0):
  167.         BaseRotatingHandler.__init__(self, filename, 'a', encoding, delay)
  168.         self.when = string.upper(when)
  169.         self.backupCount = backupCount
  170.         self.utc = utc
  171.         currentTime = int(time.time())
  172.         if self.when == 'S':
  173.             self.interval = 1
  174.             self.suffix = '%Y-%m-%d_%H-%M-%S'
  175.             self.extMatch = '^\\d{4}-\\d{2}-\\d{2}_\\d{2}-\\d{2}-\\d{2}$'
  176.         elif self.when == 'M':
  177.             self.interval = 60
  178.             self.suffix = '%Y-%m-%d_%H-%M'
  179.             self.extMatch = '^\\d{4}-\\d{2}-\\d{2}_\\d{2}-\\d{2}$'
  180.         elif self.when == 'H':
  181.             self.interval = 3600
  182.             self.suffix = '%Y-%m-%d_%H'
  183.             self.extMatch = '^\\d{4}-\\d{2}-\\d{2}_\\d{2}$'
  184.         elif self.when == 'D' or self.when == 'MIDNIGHT':
  185.             self.interval = 86400
  186.             self.suffix = '%Y-%m-%d'
  187.             self.extMatch = '^\\d{4}-\\d{2}-\\d{2}$'
  188.         elif self.when.startswith('W'):
  189.             self.interval = 604800
  190.             if len(self.when) != 2:
  191.                 raise ValueError('You must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s' % self.when)
  192.             len(self.when) != 2
  193.             if self.when[1] < '0' or self.when[1] > '6':
  194.                 raise ValueError('Invalid day specified for weekly rollover: %s' % self.when)
  195.             self.when[1] > '6'
  196.             self.dayOfWeek = int(self.when[1])
  197.             self.suffix = '%Y-%m-%d'
  198.             self.extMatch = '^\\d{4}-\\d{2}-\\d{2}$'
  199.         else:
  200.             raise ValueError('Invalid rollover interval specified: %s' % self.when)
  201.         self.extMatch = (self.when == 'MIDNIGHT').compile(self.extMatch)
  202.         self.interval = self.interval * interval
  203.         self.rolloverAt = currentTime + self.interval
  204.         if self.when == 'MIDNIGHT' or self.when.startswith('W'):
  205.             if utc:
  206.                 t = time.gmtime(currentTime)
  207.             else:
  208.                 t = time.localtime(currentTime)
  209.             currentHour = t[3]
  210.             currentMinute = t[4]
  211.             currentSecond = t[5]
  212.             r = _MIDNIGHT - ((currentHour * 60 + currentMinute) * 60 + currentSecond)
  213.             self.rolloverAt = currentTime + r
  214.             if when.startswith('W'):
  215.                 day = t[6]
  216.                 if day != self.dayOfWeek:
  217.                     if day < self.dayOfWeek:
  218.                         daysToWait = self.dayOfWeek - day
  219.                     else:
  220.                         daysToWait = (6 - day) + self.dayOfWeek + 1
  221.                     newRolloverAt = self.rolloverAt + daysToWait * 86400
  222.                     if not utc:
  223.                         dstNow = t[-1]
  224.                         dstAtRollover = time.localtime(newRolloverAt)[-1]
  225.                         if dstNow != dstAtRollover:
  226.                             if not dstNow:
  227.                                 newRolloverAt = newRolloverAt - 3600
  228.                             else:
  229.                                 newRolloverAt = newRolloverAt + 3600
  230.                         
  231.                     
  232.                     self.rolloverAt = newRolloverAt
  233.                 
  234.             
  235.         
  236.  
  237.     
  238.     def shouldRollover(self, record):
  239.         '''
  240.         Determine if rollover should occur.
  241.  
  242.         record is not used, as we are just comparing times, but it is needed so
  243.         the method signatures are the same
  244.         '''
  245.         t = int(time.time())
  246.         if t >= self.rolloverAt:
  247.             return 1
  248.         return 0
  249.  
  250.     
  251.     def getFilesToDelete(self):
  252.         '''
  253.         Determine the files to delete when rolling over.
  254.  
  255.         More specific than the earlier method, which just used glob.glob().
  256.         '''
  257.         (dirName, baseName) = os.path.split(self.baseFilename)
  258.         fileNames = os.listdir(dirName)
  259.         result = []
  260.         prefix = baseName + '.'
  261.         plen = len(prefix)
  262.         for fileName in fileNames:
  263.             if fileName[:plen] == prefix:
  264.                 suffix = fileName[plen:]
  265.                 if self.extMatch.match(suffix):
  266.                     result.append(os.path.join(dirName, fileName))
  267.                 
  268.             self.extMatch.match(suffix)
  269.         
  270.         result.sort()
  271.         if len(result) < self.backupCount:
  272.             result = []
  273.         else:
  274.             result = result[:len(result) - self.backupCount]
  275.         return result
  276.  
  277.     
  278.     def doRollover(self):
  279.         '''
  280.         do a rollover; in this case, a date/time stamp is appended to the filename
  281.         when the rollover happens.  However, you want the file to be named for the
  282.         start of the interval, not the current time.  If there is a backup count,
  283.         then we have to get a list of matching filenames, sort them and remove
  284.         the one with the oldest suffix.
  285.         '''
  286.         if self.stream:
  287.             self.stream.close()
  288.         
  289.         t = self.rolloverAt - self.interval
  290.         if self.utc:
  291.             timeTuple = time.gmtime(t)
  292.         else:
  293.             timeTuple = time.localtime(t)
  294.         dfn = self.baseFilename + '.' + time.strftime(self.suffix, timeTuple)
  295.         if os.path.exists(dfn):
  296.             os.remove(dfn)
  297.         
  298.         os.rename(self.baseFilename, dfn)
  299.         if self.backupCount > 0:
  300.             for s in self.getFilesToDelete():
  301.                 os.remove(s)
  302.             
  303.         
  304.         self.mode = 'w'
  305.         self.stream = self._open()
  306.         newRolloverAt = self.rolloverAt + self.interval
  307.         currentTime = int(time.time())
  308.         while newRolloverAt <= currentTime:
  309.             newRolloverAt = newRolloverAt + self.interval
  310.         if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not (self.utc):
  311.             dstNow = time.localtime(currentTime)[-1]
  312.             dstAtRollover = time.localtime(newRolloverAt)[-1]
  313.             if dstNow != dstAtRollover:
  314.                 if not dstNow:
  315.                     newRolloverAt = newRolloverAt - 3600
  316.                 else:
  317.                     newRolloverAt = newRolloverAt + 3600
  318.             
  319.         
  320.         self.rolloverAt = newRolloverAt
  321.  
  322.  
  323.  
  324. class WatchedFileHandler(logging.FileHandler):
  325.     '''
  326.     A handler for logging to a file, which watches the file
  327.     to see if it has changed while in use. This can happen because of
  328.     usage of programs such as newsyslog and logrotate which perform
  329.     log file rotation. This handler, intended for use under Unix,
  330.     watches the file to see if it has changed since the last emit.
  331.     (A file has changed if its device or inode have changed.)
  332.     If it has changed, the old file stream is closed, and the file
  333.     opened to get a new stream.
  334.  
  335.     This handler is not appropriate for use under Windows, because
  336.     under Windows open files cannot be moved or renamed - logging
  337.     opens the files with exclusive locks - and so there is no need
  338.     for such a handler. Furthermore, ST_INO is not supported under
  339.     Windows; stat always returns zero for this value.
  340.  
  341.     This handler is based on a suggestion and patch by Chad J.
  342.     Schroeder.
  343.     '''
  344.     
  345.     def __init__(self, filename, mode = 'a', encoding = None, delay = 0):
  346.         logging.FileHandler.__init__(self, filename, mode, encoding, delay)
  347.         if not os.path.exists(self.baseFilename):
  348.             (self.dev, self.ino) = (-1, -1)
  349.         else:
  350.             stat = os.stat(self.baseFilename)
  351.             self.dev = stat[ST_DEV]
  352.             self.ino = stat[ST_INO]
  353.  
  354.     
  355.     def emit(self, record):
  356.         '''
  357.         Emit a record.
  358.  
  359.         First check if the underlying file has changed, and if it
  360.         has, close the old stream and reopen the file to get the
  361.         current stream.
  362.         '''
  363.         if not os.path.exists(self.baseFilename):
  364.             stat = None
  365.             changed = 1
  366.         else:
  367.             stat = os.stat(self.baseFilename)
  368.             if not stat[ST_DEV] != self.dev:
  369.                 pass
  370.             changed = stat[ST_INO] != self.ino
  371.         if changed and self.stream is not None:
  372.             self.stream.flush()
  373.             self.stream.close()
  374.             self.stream = self._open()
  375.             if stat is None:
  376.                 stat = os.stat(self.baseFilename)
  377.             
  378.             self.dev = stat[ST_DEV]
  379.             self.ino = stat[ST_INO]
  380.         
  381.         logging.FileHandler.emit(self, record)
  382.  
  383.  
  384.  
  385. class SocketHandler(logging.Handler):
  386.     """
  387.     A handler class which writes logging records, in pickle format, to
  388.     a streaming socket. The socket is kept open across logging calls.
  389.     If the peer resets it, an attempt is made to reconnect on the next call.
  390.     The pickle which is sent is that of the LogRecord's attribute dictionary
  391.     (__dict__), so that the receiver does not need to have the logging module
  392.     installed in order to process the logging event.
  393.  
  394.     To unpickle the record at the receiving end into a LogRecord, use the
  395.     makeLogRecord function.
  396.     """
  397.     
  398.     def __init__(self, host, port):
  399.         """
  400.         Initializes the handler with a specific host address and port.
  401.  
  402.         The attribute 'closeOnError' is set to 1 - which means that if
  403.         a socket error occurs, the socket is silently closed and then
  404.         reopened on the next logging call.
  405.         """
  406.         logging.Handler.__init__(self)
  407.         self.host = host
  408.         self.port = port
  409.         self.sock = None
  410.         self.closeOnError = 0
  411.         self.retryTime = None
  412.         self.retryStart = 1
  413.         self.retryMax = 30
  414.         self.retryFactor = 2
  415.  
  416.     
  417.     def makeSocket(self, timeout = 1):
  418.         '''
  419.         A factory method which allows subclasses to define the precise
  420.         type of socket they want.
  421.         '''
  422.         s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  423.         if hasattr(s, 'settimeout'):
  424.             s.settimeout(timeout)
  425.         
  426.         s.connect((self.host, self.port))
  427.         return s
  428.  
  429.     
  430.     def createSocket(self):
  431.         '''
  432.         Try to create a socket, using an exponential backoff with
  433.         a max retry time. Thanks to Robert Olson for the original patch
  434.         (SF #815911) which has been slightly refactored.
  435.         '''
  436.         now = time.time()
  437.         if self.retryTime is None:
  438.             attempt = 1
  439.         else:
  440.             attempt = now >= self.retryTime
  441.         if attempt:
  442.             
  443.             try:
  444.                 self.sock = self.makeSocket()
  445.                 self.retryTime = None
  446.             except socket.error:
  447.                 if self.retryTime is None:
  448.                     self.retryPeriod = self.retryStart
  449.                 else:
  450.                     self.retryPeriod = self.retryPeriod * self.retryFactor
  451.                     if self.retryPeriod > self.retryMax:
  452.                         self.retryPeriod = self.retryMax
  453.                     
  454.                 self.retryTime = now + self.retryPeriod
  455.             except:
  456.                 None<EXCEPTION MATCH>socket.error
  457.             
  458.  
  459.         None<EXCEPTION MATCH>socket.error
  460.  
  461.     
  462.     def send(self, s):
  463.         '''
  464.         Send a pickled string to the socket.
  465.  
  466.         This function allows for partial sends which can happen when the
  467.         network is busy.
  468.         '''
  469.         if self.sock is None:
  470.             self.createSocket()
  471.         
  472.         if self.sock:
  473.             
  474.             try:
  475.                 if hasattr(self.sock, 'sendall'):
  476.                     self.sock.sendall(s)
  477.                 else:
  478.                     sentsofar = 0
  479.                     left = len(s)
  480.                     while left > 0:
  481.                         sent = self.sock.send(s[sentsofar:])
  482.                         sentsofar = sentsofar + sent
  483.                         left = left - sent
  484.             except socket.error:
  485.                 self.sock.close()
  486.                 self.sock = None
  487.             except:
  488.                 None<EXCEPTION MATCH>socket.error
  489.             
  490.  
  491.         None<EXCEPTION MATCH>socket.error
  492.  
  493.     
  494.     def makePickle(self, record):
  495.         '''
  496.         Pickles the record in binary format with a length prefix, and
  497.         returns it ready for transmission across the socket.
  498.         '''
  499.         ei = record.exc_info
  500.         if ei:
  501.             dummy = self.format(record)
  502.             record.exc_info = None
  503.         
  504.         s = cPickle.dumps(record.__dict__, 1)
  505.         if ei:
  506.             record.exc_info = ei
  507.         
  508.         slen = struct.pack('>L', len(s))
  509.         return slen + s
  510.  
  511.     
  512.     def handleError(self, record):
  513.         '''
  514.         Handle an error during logging.
  515.  
  516.         An error has occurred during logging. Most likely cause -
  517.         connection lost. Close the socket so that we can retry on the
  518.         next event.
  519.         '''
  520.         if self.closeOnError and self.sock:
  521.             self.sock.close()
  522.             self.sock = None
  523.         else:
  524.             logging.Handler.handleError(self, record)
  525.  
  526.     
  527.     def emit(self, record):
  528.         '''
  529.         Emit a record.
  530.  
  531.         Pickles the record and writes it to the socket in binary format.
  532.         If there is an error with the socket, silently drop the packet.
  533.         If there was a problem with the socket, re-establishes the
  534.         socket.
  535.         '''
  536.         
  537.         try:
  538.             s = self.makePickle(record)
  539.             self.send(s)
  540.         except (KeyboardInterrupt, SystemExit):
  541.             raise 
  542.         except:
  543.             self.handleError(record)
  544.  
  545.  
  546.     
  547.     def close(self):
  548.         '''
  549.         Closes the socket.
  550.         '''
  551.         if self.sock:
  552.             self.sock.close()
  553.             self.sock = None
  554.         
  555.         logging.Handler.close(self)
  556.  
  557.  
  558.  
  559. class DatagramHandler(SocketHandler):
  560.     """
  561.     A handler class which writes logging records, in pickle format, to
  562.     a datagram socket.  The pickle which is sent is that of the LogRecord's
  563.     attribute dictionary (__dict__), so that the receiver does not need to
  564.     have the logging module installed in order to process the logging event.
  565.  
  566.     To unpickle the record at the receiving end into a LogRecord, use the
  567.     makeLogRecord function.
  568.  
  569.     """
  570.     
  571.     def __init__(self, host, port):
  572.         '''
  573.         Initializes the handler with a specific host address and port.
  574.         '''
  575.         SocketHandler.__init__(self, host, port)
  576.         self.closeOnError = 0
  577.  
  578.     
  579.     def makeSocket(self):
  580.         '''
  581.         The factory method of SocketHandler is here overridden to create
  582.         a UDP socket (SOCK_DGRAM).
  583.         '''
  584.         s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  585.         return s
  586.  
  587.     
  588.     def send(self, s):
  589.         '''
  590.         Send a pickled string to a socket.
  591.  
  592.         This function no longer allows for partial sends which can happen
  593.         when the network is busy - UDP does not guarantee delivery and
  594.         can deliver packets out of sequence.
  595.         '''
  596.         if self.sock is None:
  597.             self.createSocket()
  598.         
  599.         self.sock.sendto(s, (self.host, self.port))
  600.  
  601.  
  602.  
  603. class SysLogHandler(logging.Handler):
  604.     """
  605.     A handler class which sends formatted logging records to a syslog
  606.     server. Based on Sam Rushing's syslog module:
  607.     http://www.nightmare.com/squirl/python-ext/misc/syslog.py
  608.     Contributed by Nicolas Untz (after which minor refactoring changes
  609.     have been made).
  610.     """
  611.     LOG_EMERG = 0
  612.     LOG_ALERT = 1
  613.     LOG_CRIT = 2
  614.     LOG_ERR = 3
  615.     LOG_WARNING = 4
  616.     LOG_NOTICE = 5
  617.     LOG_INFO = 6
  618.     LOG_DEBUG = 7
  619.     LOG_KERN = 0
  620.     LOG_USER = 1
  621.     LOG_MAIL = 2
  622.     LOG_DAEMON = 3
  623.     LOG_AUTH = 4
  624.     LOG_SYSLOG = 5
  625.     LOG_LPR = 6
  626.     LOG_NEWS = 7
  627.     LOG_UUCP = 8
  628.     LOG_CRON = 9
  629.     LOG_AUTHPRIV = 10
  630.     LOG_LOCAL0 = 16
  631.     LOG_LOCAL1 = 17
  632.     LOG_LOCAL2 = 18
  633.     LOG_LOCAL3 = 19
  634.     LOG_LOCAL4 = 20
  635.     LOG_LOCAL5 = 21
  636.     LOG_LOCAL6 = 22
  637.     LOG_LOCAL7 = 23
  638.     priority_names = {
  639.         'alert': LOG_ALERT,
  640.         'crit': LOG_CRIT,
  641.         'critical': LOG_CRIT,
  642.         'debug': LOG_DEBUG,
  643.         'emerg': LOG_EMERG,
  644.         'err': LOG_ERR,
  645.         'error': LOG_ERR,
  646.         'info': LOG_INFO,
  647.         'notice': LOG_NOTICE,
  648.         'panic': LOG_EMERG,
  649.         'warn': LOG_WARNING,
  650.         'warning': LOG_WARNING }
  651.     facility_names = {
  652.         'auth': LOG_AUTH,
  653.         'authpriv': LOG_AUTHPRIV,
  654.         'cron': LOG_CRON,
  655.         'daemon': LOG_DAEMON,
  656.         'kern': LOG_KERN,
  657.         'lpr': LOG_LPR,
  658.         'mail': LOG_MAIL,
  659.         'news': LOG_NEWS,
  660.         'security': LOG_AUTH,
  661.         'syslog': LOG_SYSLOG,
  662.         'user': LOG_USER,
  663.         'uucp': LOG_UUCP,
  664.         'local0': LOG_LOCAL0,
  665.         'local1': LOG_LOCAL1,
  666.         'local2': LOG_LOCAL2,
  667.         'local3': LOG_LOCAL3,
  668.         'local4': LOG_LOCAL4,
  669.         'local5': LOG_LOCAL5,
  670.         'local6': LOG_LOCAL6,
  671.         'local7': LOG_LOCAL7 }
  672.     priority_map = {
  673.         'DEBUG': 'debug',
  674.         'INFO': 'info',
  675.         'WARNING': 'warning',
  676.         'ERROR': 'error',
  677.         'CRITICAL': 'critical' }
  678.     
  679.     def __init__(self, address = ('localhost', SYSLOG_UDP_PORT), facility = LOG_USER):
  680.         '''
  681.         Initialize a handler.
  682.  
  683.         If address is specified as a string, a UNIX socket is used. To log to a
  684.         local syslogd, "SysLogHandler(address="/dev/log")" can be used.
  685.         If facility is not specified, LOG_USER is used.
  686.         '''
  687.         logging.Handler.__init__(self)
  688.         self.address = address
  689.         self.facility = facility
  690.         if type(address) == types.StringType:
  691.             self.unixsocket = 1
  692.             self._connect_unixsocket(address)
  693.         else:
  694.             self.unixsocket = 0
  695.             self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  696.         self.formatter = None
  697.  
  698.     
  699.     def _connect_unixsocket(self, address):
  700.         self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
  701.         
  702.         try:
  703.             self.socket.connect(address)
  704.         except socket.error:
  705.             self.socket.close()
  706.             self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  707.             self.socket.connect(address)
  708.  
  709.  
  710.     log_format_string = '<%d>%s\x00'
  711.     
  712.     def encodePriority(self, facility, priority):
  713.         '''
  714.         Encode the facility and priority. You can pass in strings or
  715.         integers - if strings are passed, the facility_names and
  716.         priority_names mapping dictionaries are used to convert them to
  717.         integers.
  718.         '''
  719.         if type(facility) == types.StringType:
  720.             facility = self.facility_names[facility]
  721.         
  722.         if type(priority) == types.StringType:
  723.             priority = self.priority_names[priority]
  724.         
  725.         return facility << 3 | priority
  726.  
  727.     
  728.     def close(self):
  729.         '''
  730.         Closes the socket.
  731.         '''
  732.         if self.unixsocket:
  733.             self.socket.close()
  734.         
  735.         logging.Handler.close(self)
  736.  
  737.     
  738.     def mapPriority(self, levelName):
  739.         """
  740.         Map a logging level name to a key in the priority_names map.
  741.         This is useful in two scenarios: when custom levels are being
  742.         used, and in the case where you can't do a straightforward
  743.         mapping by lowercasing the logging level name because of locale-
  744.         specific issues (see SF #1524081).
  745.         """
  746.         return self.priority_map.get(levelName, 'warning')
  747.  
  748.     
  749.     def emit(self, record):
  750.         '''
  751.         Emit a record.
  752.  
  753.         The record is formatted, and then sent to the syslog server. If
  754.         exception information is present, it is NOT sent to the server.
  755.         '''
  756.         msg = self.format(record)
  757.         msg = self.log_format_string % (self.encodePriority(self.facility, self.mapPriority(record.levelname)), msg)
  758.         
  759.         try:
  760.             if self.unixsocket:
  761.                 
  762.                 try:
  763.                     self.socket.send(msg)
  764.                 except socket.error:
  765.                     self._connect_unixsocket(self.address)
  766.                     self.socket.send(msg)
  767.                 except:
  768.                     None<EXCEPTION MATCH>socket.error
  769.                 
  770.  
  771.             None<EXCEPTION MATCH>socket.error
  772.             self.socket.sendto(msg, self.address)
  773.         except (KeyboardInterrupt, SystemExit):
  774.             raise 
  775.         except:
  776.             self.handleError(record)
  777.  
  778.  
  779.  
  780.  
  781. class SMTPHandler(logging.Handler):
  782.     '''
  783.     A handler class which sends an SMTP email for each logging event.
  784.     '''
  785.     
  786.     def __init__(self, mailhost, fromaddr, toaddrs, subject, credentials = None):
  787.         '''
  788.         Initialize the handler.
  789.  
  790.         Initialize the instance with the from and to addresses and subject
  791.         line of the email. To specify a non-standard SMTP port, use the
  792.         (host, port) tuple format for the mailhost argument. To specify
  793.         authentication credentials, supply a (username, password) tuple
  794.         for the credentials argument.
  795.         '''
  796.         logging.Handler.__init__(self)
  797.         if type(mailhost) == types.TupleType:
  798.             (self.mailhost, self.mailport) = mailhost
  799.         else:
  800.             self.mailhost = mailhost
  801.             self.mailport = None
  802.         if type(credentials) == types.TupleType:
  803.             (self.username, self.password) = credentials
  804.         else:
  805.             self.username = None
  806.         self.fromaddr = fromaddr
  807.         if type(toaddrs) == types.StringType:
  808.             toaddrs = [
  809.                 toaddrs]
  810.         
  811.         self.toaddrs = toaddrs
  812.         self.subject = subject
  813.  
  814.     
  815.     def getSubject(self, record):
  816.         '''
  817.         Determine the subject for the email.
  818.  
  819.         If you want to specify a subject line which is record-dependent,
  820.         override this method.
  821.         '''
  822.         return self.subject
  823.  
  824.     weekdayname = [
  825.         'Mon',
  826.         'Tue',
  827.         'Wed',
  828.         'Thu',
  829.         'Fri',
  830.         'Sat',
  831.         'Sun']
  832.     monthname = [
  833.         None,
  834.         'Jan',
  835.         'Feb',
  836.         'Mar',
  837.         'Apr',
  838.         'May',
  839.         'Jun',
  840.         'Jul',
  841.         'Aug',
  842.         'Sep',
  843.         'Oct',
  844.         'Nov',
  845.         'Dec']
  846.     
  847.     def date_time(self):
  848.         '''
  849.         Return the current date and time formatted for a MIME header.
  850.         Needed for Python 1.5.2 (no email package available)
  851.         '''
  852.         (year, month, day, hh, mm, ss, wd, y, z) = time.gmtime(time.time())
  853.         s = '%s, %02d %3s %4d %02d:%02d:%02d GMT' % (self.weekdayname[wd], day, self.monthname[month], year, hh, mm, ss)
  854.         return s
  855.  
  856.     
  857.     def emit(self, record):
  858.         '''
  859.         Emit a record.
  860.  
  861.         Format the record and send it to the specified addressees.
  862.         '''
  863.         
  864.         try:
  865.             import smtplib
  866.             
  867.             try:
  868.                 formatdate = formatdate
  869.                 import email.utils
  870.             except ImportError:
  871.                 formatdate = self.date_time
  872.  
  873.             port = self.mailport
  874.             if not port:
  875.                 port = smtplib.SMTP_PORT
  876.             
  877.             smtp = smtplib.SMTP(self.mailhost, port)
  878.             msg = self.format(record)
  879.             msg = 'From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s' % (self.fromaddr, string.join(self.toaddrs, ','), self.getSubject(record), formatdate(), msg)
  880.             if self.username:
  881.                 smtp.login(self.username, self.password)
  882.             
  883.             smtp.sendmail(self.fromaddr, self.toaddrs, msg)
  884.             smtp.quit()
  885.         except (KeyboardInterrupt, SystemExit):
  886.             raise 
  887.         except:
  888.             self.handleError(record)
  889.  
  890.  
  891.  
  892.  
  893. class NTEventLogHandler(logging.Handler):
  894.     '''
  895.     A handler class which sends events to the NT Event Log. Adds a
  896.     registry entry for the specified application name. If no dllname is
  897.     provided, win32service.pyd (which contains some basic message
  898.     placeholders) is used. Note that use of these placeholders will make
  899.     your event logs big, as the entire message source is held in the log.
  900.     If you want slimmer logs, you have to pass in the name of your own DLL
  901.     which contains the message definitions you want to use in the event log.
  902.     '''
  903.     
  904.     def __init__(self, appname, dllname = None, logtype = 'Application'):
  905.         logging.Handler.__init__(self)
  906.         
  907.         try:
  908.             import win32evtlogutil
  909.             import win32evtlog
  910.             self.appname = appname
  911.             self._welu = win32evtlogutil
  912.             if not dllname:
  913.                 dllname = os.path.split(self._welu.__file__)
  914.                 dllname = os.path.split(dllname[0])
  915.                 dllname = os.path.join(dllname[0], 'win32service.pyd')
  916.             
  917.             self.dllname = dllname
  918.             self.logtype = logtype
  919.             self._welu.AddSourceToRegistry(appname, dllname, logtype)
  920.             self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE
  921.             self.typemap = {
  922.                 logging.DEBUG: win32evtlog.EVENTLOG_INFORMATION_TYPE,
  923.                 logging.INFO: win32evtlog.EVENTLOG_INFORMATION_TYPE,
  924.                 logging.WARNING: win32evtlog.EVENTLOG_WARNING_TYPE,
  925.                 logging.ERROR: win32evtlog.EVENTLOG_ERROR_TYPE,
  926.                 logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE }
  927.         except ImportError:
  928.             print 'The Python Win32 extensions for NT (service, event logging) appear not to be available.'
  929.             self._welu = None
  930.  
  931.  
  932.     
  933.     def getMessageID(self, record):
  934.         '''
  935.         Return the message ID for the event record. If you are using your
  936.         own messages, you could do this by having the msg passed to the
  937.         logger being an ID rather than a formatting string. Then, in here,
  938.         you could use a dictionary lookup to get the message ID. This
  939.         version returns 1, which is the base message ID in win32service.pyd.
  940.         '''
  941.         return 1
  942.  
  943.     
  944.     def getEventCategory(self, record):
  945.         '''
  946.         Return the event category for the record.
  947.  
  948.         Override this if you want to specify your own categories. This version
  949.         returns 0.
  950.         '''
  951.         return 0
  952.  
  953.     
  954.     def getEventType(self, record):
  955.         """
  956.         Return the event type for the record.
  957.  
  958.         Override this if you want to specify your own types. This version does
  959.         a mapping using the handler's typemap attribute, which is set up in
  960.         __init__() to a dictionary which contains mappings for DEBUG, INFO,
  961.         WARNING, ERROR and CRITICAL. If you are using your own levels you will
  962.         either need to override this method or place a suitable dictionary in
  963.         the handler's typemap attribute.
  964.         """
  965.         return self.typemap.get(record.levelno, self.deftype)
  966.  
  967.     
  968.     def emit(self, record):
  969.         '''
  970.         Emit a record.
  971.  
  972.         Determine the message ID, event category and event type. Then
  973.         log the message in the NT event log.
  974.         '''
  975.         if self._welu:
  976.             
  977.             try:
  978.                 id = self.getMessageID(record)
  979.                 cat = self.getEventCategory(record)
  980.                 type = self.getEventType(record)
  981.                 msg = self.format(record)
  982.                 self._welu.ReportEvent(self.appname, id, cat, type, [
  983.                     msg])
  984.             except (KeyboardInterrupt, SystemExit):
  985.                 raise 
  986.             except:
  987.                 None<EXCEPTION MATCH>(KeyboardInterrupt, SystemExit)
  988.                 self.handleError(record)
  989.             
  990.  
  991.         None<EXCEPTION MATCH>(KeyboardInterrupt, SystemExit)
  992.  
  993.     
  994.     def close(self):
  995.         '''
  996.         Clean up this handler.
  997.  
  998.         You can remove the application name from the registry as a
  999.         source of event log entries. However, if you do this, you will
  1000.         not be able to see the events as you intended in the Event Log
  1001.         Viewer - it needs to be able to access the registry to get the
  1002.         DLL name.
  1003.         '''
  1004.         logging.Handler.close(self)
  1005.  
  1006.  
  1007.  
  1008. class HTTPHandler(logging.Handler):
  1009.     '''
  1010.     A class which sends records to a Web server, using either GET or
  1011.     POST semantics.
  1012.     '''
  1013.     
  1014.     def __init__(self, host, url, method = 'GET'):
  1015.         '''
  1016.         Initialize the instance with the host, the request URL, and the method
  1017.         ("GET" or "POST")
  1018.         '''
  1019.         logging.Handler.__init__(self)
  1020.         method = string.upper(method)
  1021.         if method not in ('GET', 'POST'):
  1022.             raise ValueError, 'method must be GET or POST'
  1023.         method not in ('GET', 'POST')
  1024.         self.host = host
  1025.         self.url = url
  1026.         self.method = method
  1027.  
  1028.     
  1029.     def mapLogRecord(self, record):
  1030.         '''
  1031.         Default implementation of mapping the log record into a dict
  1032.         that is sent as the CGI data. Overwrite in your class.
  1033.         Contributed by Franz  Glasner.
  1034.         '''
  1035.         return record.__dict__
  1036.  
  1037.     
  1038.     def emit(self, record):
  1039.         '''
  1040.         Emit a record.
  1041.  
  1042.         Send the record to the Web server as an URL-encoded dictionary
  1043.         '''
  1044.         
  1045.         try:
  1046.             import httplib
  1047.             import urllib
  1048.             host = self.host
  1049.             h = httplib.HTTP(host)
  1050.             url = self.url
  1051.             data = urllib.urlencode(self.mapLogRecord(record))
  1052.             if self.method == 'GET':
  1053.                 if string.find(url, '?') >= 0:
  1054.                     sep = '&'
  1055.                 else:
  1056.                     sep = '?'
  1057.                 url = url + '%c%s' % (sep, data)
  1058.             
  1059.             h.putrequest(self.method, url)
  1060.             i = string.find(host, ':')
  1061.             if i >= 0:
  1062.                 host = host[:i]
  1063.             
  1064.             h.putheader('Host', host)
  1065.             if self.method == 'POST':
  1066.                 h.putheader('Content-type', 'application/x-www-form-urlencoded')
  1067.                 h.putheader('Content-length', str(len(data)))
  1068.             
  1069.             h.endheaders()
  1070.             if self.method == 'POST':
  1071.                 h.send(data)
  1072.             
  1073.             h.getreply()
  1074.         except (KeyboardInterrupt, SystemExit):
  1075.             raise 
  1076.         except:
  1077.             self.handleError(record)
  1078.  
  1079.  
  1080.  
  1081.  
  1082. class BufferingHandler(logging.Handler):
  1083.     """
  1084.   A handler class which buffers logging records in memory. Whenever each
  1085.   record is added to the buffer, a check is made to see if the buffer should
  1086.   be flushed. If it should, then flush() is expected to do what's needed.
  1087.     """
  1088.     
  1089.     def __init__(self, capacity):
  1090.         '''
  1091.         Initialize the handler with the buffer size.
  1092.         '''
  1093.         logging.Handler.__init__(self)
  1094.         self.capacity = capacity
  1095.         self.buffer = []
  1096.  
  1097.     
  1098.     def shouldFlush(self, record):
  1099.         '''
  1100.         Should the handler flush its buffer?
  1101.  
  1102.         Returns true if the buffer is up to capacity. This method can be
  1103.         overridden to implement custom flushing strategies.
  1104.         '''
  1105.         return len(self.buffer) >= self.capacity
  1106.  
  1107.     
  1108.     def emit(self, record):
  1109.         '''
  1110.         Emit a record.
  1111.  
  1112.         Append the record. If shouldFlush() tells us to, call flush() to process
  1113.         the buffer.
  1114.         '''
  1115.         self.buffer.append(record)
  1116.         if self.shouldFlush(record):
  1117.             self.flush()
  1118.         
  1119.  
  1120.     
  1121.     def flush(self):
  1122.         '''
  1123.         Override to implement custom flushing behaviour.
  1124.  
  1125.         This version just zaps the buffer to empty.
  1126.         '''
  1127.         self.buffer = []
  1128.  
  1129.     
  1130.     def close(self):
  1131.         """
  1132.         Close the handler.
  1133.  
  1134.         This version just flushes and chains to the parent class' close().
  1135.         """
  1136.         self.flush()
  1137.         logging.Handler.close(self)
  1138.  
  1139.  
  1140.  
  1141. class MemoryHandler(BufferingHandler):
  1142.     '''
  1143.     A handler class which buffers logging records in memory, periodically
  1144.     flushing them to a target handler. Flushing occurs whenever the buffer
  1145.     is full, or when an event of a certain severity or greater is seen.
  1146.     '''
  1147.     
  1148.     def __init__(self, capacity, flushLevel = logging.ERROR, target = None):
  1149.         '''
  1150.         Initialize the handler with the buffer size, the level at which
  1151.         flushing should occur and an optional target.
  1152.  
  1153.         Note that without a target being set either here or via setTarget(),
  1154.         a MemoryHandler is no use to anyone!
  1155.         '''
  1156.         BufferingHandler.__init__(self, capacity)
  1157.         self.flushLevel = flushLevel
  1158.         self.target = target
  1159.  
  1160.     
  1161.     def shouldFlush(self, record):
  1162.         '''
  1163.         Check for buffer full or a record at the flushLevel or higher.
  1164.         '''
  1165.         if not len(self.buffer) >= self.capacity:
  1166.             pass
  1167.         return record.levelno >= self.flushLevel
  1168.  
  1169.     
  1170.     def setTarget(self, target):
  1171.         '''
  1172.         Set the target handler for this handler.
  1173.         '''
  1174.         self.target = target
  1175.  
  1176.     
  1177.     def flush(self):
  1178.         '''
  1179.         For a MemoryHandler, flushing means just sending the buffered
  1180.         records to the target, if there is one. Override if you want
  1181.         different behaviour.
  1182.         '''
  1183.         if self.target:
  1184.             for record in self.buffer:
  1185.                 self.target.handle(record)
  1186.             
  1187.             self.buffer = []
  1188.         
  1189.  
  1190.     
  1191.     def close(self):
  1192.         '''
  1193.         Flush, set the target to None and lose the buffer.
  1194.         '''
  1195.         self.flush()
  1196.         self.target = None
  1197.         BufferingHandler.close(self)
  1198.  
  1199.  
  1200.